package com.xvdong.gadget;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Created by xvDong on 2025/5/26.
 * 申请软件著作权需要的源代码整理
 */
public class JavaKotlinFileExtractor {

    public static void main(String[] args) {
        // 替换为你的目录路径
        String directoryPath = "C:\\code\\newGitProject\\FlipMirrorMate200";
        String outputFile = "Mate200.txt";

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
            List<Path> allFiles = Files.walk(Paths.get(directoryPath))
                    .filter(Files::isRegularFile)
                    .filter(path -> path.toString().endsWith(".java") || path.toString().endsWith(".kt"))
                    .collect(Collectors.toList());

            // 优先包含"Main"的文件
            List<Path> sortedFiles = allFiles.stream()
                    .sorted((p1, p2) -> {
                        boolean p1IsMain = p1.getFileName().toString().contains("Main");
                        boolean p2IsMain = p2.getFileName().toString().contains("Main");
                        return Boolean.compare(!p1IsMain, !p2IsMain); // true靠后，false靠前
                    })
                    .collect(Collectors.toList());

            for (Path path : sortedFiles) {
                processFile(path, writer);
            }

            System.out.println("提取完成，结果保存在 " + outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void processFile(Path filePath, BufferedWriter writer) {
        try {
            String content = Files.readString(filePath);

            // 删除多行注释
            content = content.replaceAll("(?s)/\\*.*?\\*/", "");

            // 删除单行注释
            content = content.replaceAll("(?m)//.*$", "");

            // 去除空行
            String[] lines = content.split("\r?\n");
            for (String line : lines) {
                if (!line.trim().isEmpty()) {
                    writer.write(line);
                    writer.newLine();
                }
            }
            writer.newLine(); // 文件之间加分隔
        } catch (IOException e) {
            System.err.println("无法读取文件: " + filePath);
            e.printStackTrace();
        }
    }
}